package com.test32_网络编程.echo.server;

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class EchoServer {

    public static void main(String[] args) throws Exception {
//        test1();
        test2();
    }

    /**
     * Echo模型
     */
    public static void test1() throws Exception {
        ServerSocket serverSocket = new ServerSocket(9999); // 绑定端口
        Socket client = serverSocket.accept();  // 进入阻塞状态，等待客户端连接
        Scanner scanner = new Scanner(client.getInputStream());         // 客户端输入流
        PrintStream out = new PrintStream(client.getOutputStream());    // 客户端输出流
        boolean flag = true;
        while (flag) {
            if (scanner.hasNext()) {
                String value = scanner.next().trim();
                if (value.equalsIgnoreCase("exit")) {   // 结束交互
                    out.println("【EchoServer】信息服务交互完毕，已经断开与服务器的连接");
                    flag = false;   // 停止交互
                    break;
                }
                out.println("ECHO:" + value);
            }
        }
        serverSocket.close();
    }

    /**
     * BIO模型，同步阻塞IO
     */
    public static void test2() throws Exception {
        ServerSocket serverSocket = new ServerSocket(9999); // 绑定端口
        boolean flag = true;
        while (flag) {
            Socket client = serverSocket.accept();  // 进入阻塞状态，等待客户端连接
            new Thread(new EchoHandle(client)).start(); // 启动线程
        }
        serverSocket.close();
    }
}
